import Request from 'luch-request'
const http2 = new Request();
import {
	useLoginStore
} from '../stores/login.store.js'

const loginStore = useLoginStore()

const http = new Request({
	baseURL: 'https://letaoapi.jxsaichuang.com', // 基础路径
	timeout: 30000, // 超时时间
	header: {
		'Content-Type': 'application/json'
	}
})

// 请求拦截器
http.interceptors.request.use(
	(config) => {
		if (loginStore.Token) {
			config.header = config.header || {};
			config.header['token'] = loginStore.Token
		}
		return config
	},
	(error) => {
		return Promise.reject(error)
	}
)

// 响应拦截器
http.interceptors.response.use(
	(response) => {
		return response.data
	},
	async (error) => {
		const {
			statusCode,
			config
		} = error
		try {
			if (statusCode === 401) {
				let {
					data
				} = await http2.post('http://47.98.187.80:5000/api/refreshToken', {
					refreshToken: loginStore.RefreshToken
				})
				let {
					token,
					userInfo
				} = data
				loginStore.Token = token
				loginStore.UserInfo = userInfo
				return http.request(config)
			} else {
				return Promise.reject(error)
			}
		} catch (err) {
			console.log('err=>', err);
			loginStore.goLogin()
		}
	}
)

export default http